﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using YuuzleComic.DBUtility;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NPinyin;
using System.Net;
using YuuzleComic.Common;
using System.IO;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
public partial class yzadmin_data_Comics : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    JObject result = new JObject();
    YuuzleComic.BLL.zz zzbll = new YuuzleComic.BLL.zz();
    YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
    YuuzleComic.BLL.comics comicbll = new YuuzleComic.BLL.comics();
    YuuzleComic.BLL.ycclass classbll = new YuuzleComic.BLL.ycclass();
    YuuzleComic.BLL.diqu diqubll = new YuuzleComic.BLL.diqu();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "updatecolumn":
                    this.ProcessUpdateColumn();
                    break;
                case "delete":
                    this.ProcessDelete();
                    break;
                case "save":
                    this.ProcessSave();
                    break;
                case "allid":
                    this.ProcessAllId();
                    break;
                case "check":
                    this.ProcessCheck();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessCheck()
    {
        try
        {
            string[] mhmcArr = Request["mhmc"].Split('^');
            JArray data = new JArray();
            foreach (string item in mhmcArr)
            {
                JObject jo = new JObject();
                jo.Add("mhmc", item);
                jo.Add("exist", DbHelperSQL.Exists("select top(1) id from search where contains(mc1,@mhmc)", new SqlParameter[] { new SqlParameter("@mhmc", "\"" + item.Replace("|", "\" or \"") + "\"") }));
                data.Add(jo);
            }
            result.Add("success", true);
            result.Add("data", data);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessAllId()
    {
        try
        {
            DataSet ds = DbHelperSQL.Query("select id from comics");
            List<int> idList = new List<int>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                idList.Add(Convert.ToInt32(dr["id"]));
            }
            result.Add("success", true);
            result.Add("allid", JArray.FromObject(idList));
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessSave()
    {
        try
        {
            YuuzleComic.Model.comics comic = new YuuzleComic.Model.comics();
            if (!string.IsNullOrEmpty(Request.Form["id"]))
            {
                comic = comicbll.GetModel(Convert.ToInt32(Request.Form["id"]));
            }
            comic.mhmc = Request.Form["mhmc"];
            //comic.zzid = int.Parse(Request.Form["zzid"]);
            comic.zm = Request.Form["zm"];
            comic.zt = Request.Form["zt"] == "on";
            comic.mhfm = Request.Form["mhfm"];
            comic.mhjs = YuuzleComic.Common.Input.convertHtml(Request.Form["mhjs"].Trim());
            comic.dqid = Convert.ToInt32(Request.Form["dqid"]);
            comic.classid = Convert.ToInt32(Request.Form["classid"]);
            comic.tj = Request.Form["tj"] == "on";
            comic.mhbm = Request.Form["mhbm"];
            if (!string.IsNullOrEmpty(Request.Form["mhtc"]))
            {
                comic.mhtc = Request.Form["mhtc"];
            }
            if (!string.IsNullOrEmpty(Request.Form["mhjj"]))
            {
                comic.mhjj = Request.Form["mhjj"];
            }
            else
            {
                comic.mhjj = Input.GetSubString(Input.FilterHTML(comic.mhjs).Trim(), 300, "…");
            }
            if (string.IsNullOrEmpty(comic.zm))
            {
                comic.zm = Pinyin.GetInitials(comic.mhmc).Substring(0, 1);
            }
            if (string.IsNullOrEmpty(Request.Form["id"]))
            {
                comic.adddate = DateTime.Now;
                //comic.mhjs = YuuzleComic.Common.Input.getComicContent(comic.mhjs, DbHelperSQL.Query("select top(1) text from segment order by newid()").Tables[0].Rows[0][0].ToString());
                comic.id = comicbll.Add(comic);
            }
            else
            {
                comic.id = Convert.ToInt32(Request.Form["id"]);
                comicbll.Update(comic);
            }
            if (!string.IsNullOrEmpty(Request.Form["zzmc"].Trim()))
            {
                DbHelperSQL.ExecuteSql("delete from comics_zz where cid=" + comic.id);
                foreach (string zzmc in Request.Form["zzmc"].Trim().Split(','))
                {
                    int zzid = zzbll.GetIdByName(zzmc.Trim());
                    if (zzid == 0)
                    {
                        YuuzleComic.Model.zz zz = new YuuzleComic.Model.zz();
                        zz.zzmc = zzmc.Trim();
                        zz.zzjs = "<h2 class=\"blue\">" + zz.zzmc + "漫画全集</h2>";
                        zz.dqid = comic.dqid;
                        zz.zztp = "none.jpg";
                        zz.tj = comic.tj;
                        zz.zm = Pinyin.GetInitials(zz.zzmc).Substring(0, 1);
                        zzid = zzbll.Add(zz);
                    }
                    DbHelperSQL.ExecuteSql("insert into comics_zz (cid,zzid) values (" + comic.id + "," + zzid + ")");
                }
            }
            this.process_mhfm(comic);
            this.process_mhzj(comic);
            this.process_search(comic);
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void process_search(YuuzleComic.Model.comics comic)
    {
        DbHelperSQL.Query("delete from search where cid=" + comic.id);
        List<string> mclist = new List<string>();
        mclist.Add(comic.mhmc);
        if (!string.IsNullOrEmpty(comic.mhbm))
        {
            foreach (string item in comic.mhbm.Split(','))
            {
                mclist.Add(item);
            }
        }
        //更新索引
        foreach (string mc in mclist)
        {
            SqlParameter[] parameters = {
					new SqlParameter("@cid", SqlDbType.Int),
                    new SqlParameter("@mc1", SqlDbType.VarChar),
                    new SqlParameter("@mc2", SqlDbType.VarChar),
                    new SqlParameter("@mc3", SqlDbType.VarChar),
                    new SqlParameter("@mc4", SqlDbType.VarChar),
                    new SqlParameter("@mc5", SqlDbType.VarChar)};
            parameters[0].Value = comic.id;
            parameters[1].Value = mc;
            parameters[2].Value = Strings.StrConv(mc, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, System.Globalization.CultureInfo.CurrentCulture.LCID);
            parameters[3].Value = Pinyin.GetPinyin(mc).Replace(" ", "");
            parameters[4].Value = Pinyin.GetInitials(mc).Replace(" ", "");
            parameters[5].Value = Request.Form["zzmc"].Trim();
            DbHelperSQL.Query("insert into search (cid,mc1,mc2,mc3,mc4,mc5) values(@cid,@mc1,@mc2,@mc3,@mc4,@mc5)", parameters);
        }
    }

    private void ProcessSingle()
    {
        try
        {
            DataSet ds = DbHelperSQL.Query("select mhjs,mhjj from comics where id=" + Request["id"]);
            result.Add("success", true);
            result.Add("data", JArray.FromObject(ds.Tables[0])[0]);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessDelete()
    {
        try
        {
            DbHelperSQL.ExecuteSql("delete from comics where id in (" + Request["ids"] + ")");
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessUpdateColumn()
    {
        try
        {
            DbHelperSQL.ExecuteSql("update comics set " + Request["column"] + "=" + Request["value"] + " where id=" + Request["id"]);
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessUpdateTJ()
    {
        throw new NotImplementedException();
    }

    private void ProcessList()
    {
        try
        {
            int start = Convert.ToInt32(Request["start"]);
            int limit = Convert.ToInt32(Request["limit"]);
            string query = Request["query"] != null ? YuuzleComic.Common.Input.Filter(Request["query"]) : "";
            string strWhere = "where mhmc like @query or mhbm like @query or zzmc like @query";
            if (!string.IsNullOrEmpty(Request["mhmc"]))
            {
                strWhere = "where mhmc=@mhmc or mhbm=@mhmc";
            }
            string sql = "with tt as(Select ROW_NUMBER() Over(order by " + Request["sort"] + " " + Request["dir"] + ") as rowNum,* from ";
            sql += "(Select a.id, a.classid, a.mhmc, a.dqid, a.zm, a.zt, a.mhfm, a.hits_d, ";
            sql += "a.hits_d_d, a.hits_w, a.hits_w_d, a.hits_m, a.hits_m_d, a.hits, a.adddate, a.tj, ";
            sql += "a.cjid, a.cjitemid, a.mhtc, a.mhbm, b.diqu, c.classname, f.time, e.zjcount,";
            //sql += "STUFF((select ',' +cast(zzid as varchar) from comics_zz where cid=a.id FOR XML PATH('')), 1, 1, '') zzid,";
            sql += "STUFF((SELECT ','+ z.zzmc FROM zz z join comics_zz cz on z.id=cz.zzid where cz.cid=a.id FOR XML PATH('')), 1, 1, '') zzmc ";
            sql += "FROM comics a LEFT OUTER JOIN diqu b ON a.dqid = b.id LEFT OUTER JOIN class c ON a.classid = c.id LEFT OUTER JOIN ";
            sql += "(SELECT cid, MAX(id) AS maxid, COUNT(id) AS zjcount FROM zj GROUP BY cid) AS e ON a.id = e.cid LEFT OUTER JOIN zj AS f ON e.maxid = f.id) t ";
            sql += strWhere;
            sql += ") select * from TT where rowNum between @start and @end";
            SqlParameter[] parameters = new SqlParameter[] { 
                 new SqlParameter("@query","%" +query + "%"),
                 new SqlParameter("@mhmc",Request["mhmc"]),
                new SqlParameter("@start",start + 1),
                new SqlParameter("@end",start + limit)
            };
            DataSet ds = DbHelperSQL.Query(sql, parameters);
            int total = Convert.ToInt32(DbHelperSQL.Query("select count(id) from (select a.id,a.mhmc,a.mhbm,STUFF((SELECT ','+ z.zzmc FROM zz z join comics_zz cz on z.id=cz.zzid where cz.cid=a.id FOR XML PATH('')), 1, 1, '') zzmc from comics a) t " + strWhere, parameters).Tables[0].Rows[0][0]);
            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;
            result.Add("data", JArray.FromObject(ds.Tables[0], serializer));
            result.Add("total", total);
            json = result.ToString();
        }
        catch (Exception)
        {

            throw;
        }
    }

    private void process_mhfm(YuuzleComic.Model.comics comic)
    {
        if (comic.mhfm.Contains("http://"))
        {
            string filename = comic.id + ".jpg";
            WebClient wc = new WebClient();
            if (comic.mhfm.Contains(ConfigurationManager.AppSettings.Get("ProxyDomain")))
            {
                wc.Proxy = new WebProxy(ConfigurationManager.AppSettings.Get("Proxy"));
            }
            byte[] b = wc.DownloadData(comic.mhfm);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Input.ResizeImageFile(b, 120, 160));
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            img.Save(Server.MapPath("~/cpic/" + filename), System.Drawing.Imaging.ImageFormat.Jpeg);
            DbHelperSQL.ExecuteSql("update comics set mhfm='" + filename + "' where id=" + comic.id);
        }
    }

    private void process_mhzj(YuuzleComic.Model.comics comic)
    {
        string comicdir = Request.Form["comicdir"].Trim();
        string comicFolder = "";
        foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
        {
            if (Directory.Exists(item.Value + comicdir))
            {
                comicFolder = item.Value + comicdir;
                break;
            }
        }
        if (!string.IsNullOrEmpty(comicdir) && !string.IsNullOrEmpty(comicFolder))
        {
            DirectoryInfo cdir = new DirectoryInfo(comicFolder);
            foreach (DirectoryInfo zdir in cdir.GetDirectories())
            {
                List<string> imglist = new List<string>();
                foreach (FileInfo f in zdir.GetFiles())
                {
                    if (f.Name != "Thumbs.db")
                    {
                        imglist.Add(f.Name);
                    }
                }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.time = DateTime.Now;
                zj.cid = comic.id;
                zj.isdownload = true;
                zj.tpurl = string.Join("|", imglist.ToArray());
                if (zdir.Name.ToLower().Contains("act_"))
                {
                    zj.zjmc = "第" + zdir.Name.Split('_')[1] + "话";
                }
                else if (zdir.Name.ToLower().Contains("vol_"))
                {
                    zj.zjmc = "第" + zdir.Name.Split('_')[1] + "卷";
                }
                else
                {
                    zj.zjmc = zdir.Name;
                }
                zj.tpadd = comicdir + zdir.Name + "/";
                zj.tps = imglist.Count;
                if (!zjbll.ExistsAdd(zj.tpadd, zj.cid))
                {
                    zjbll.Add(zj);
                }
            }
        }
    }
}